from django.template import loader
import os, time
from django.conf import settings

from contents.utils import get_categories
from contents.models import ContentCategory, Content


def generate_static_index_html():
    """
    生成静态的主页html文件
    """
    print('%s: generate_static_index_html' % time.ctime())

    # 查询首页相关数据
    # 查询商品分类
    categories = get_categories()

    # 查询首页广告
    # 准备首页广告数据字典
    contents = {}
    # 查询所有的广告分类数据
    content_categories = ContentCategory.objects.all()
    # 遍历广告分类并提取key
    for content_cat in content_categories:
        contents[content_cat.key] = Content.objects.filter(category=content_cat, status=True).order_by('sequence')

    # 构造上下文
    context = {
        'categories': categories,
        'contents': contents
    }

    # 获取首页模板文件
    template = loader.get_template('index.html')
    # 渲染首页html字符串
    index_html_text = template.render(context)

    # 将首页html字符串写入到指定目录，命名'index.html'
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:  # encoding='utf-8' 搭配定时任务解决中文出错的问题
        f.write(index_html_text)


    """
    template = loader.get_template('index.html')
    index_html_text = template.render(context)
    return http.HttpReponse(index_html_text)
    ==
    return render(request, 'index.html', context)
    """

